package com.hong.utils;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: Administrator
 * @Date: 2018/7/22 20:07
 * @Description:
 */
public class CyclicBarrierExample3 {

    static class MyCountDownLatch extends CountDownLatch{
        private final Runnable runnable;
        /**
         * Constructs a {@code CountDownLatch} initialized with the given count.
         *
         * @param count the number of times {@link #countDown} must be invoked
         *              before threads can pass through {@link #await}
         * @param runnable
         * @throws IllegalArgumentException if {@code count} is negative
         */
        public MyCountDownLatch(int count, Runnable runnable) {
            super(count);
            this.runnable = runnable;
        }

        @Override
        public void countDown() {
            super.countDown();
            if(getCount()==0){
                this.runnable.run();
            }
        }
    }

    public static void main(String[] args) {
        final  MyCountDownLatch myCountDownLatch = new MyCountDownLatch(2, new Runnable() {
            public void run() {
                System.out.println("all of work finish done.");
            }
        });

        new Thread(){
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                myCountDownLatch.countDown();
                System.out.println(Thread.currentThread().getName()+"finished.");
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                myCountDownLatch.countDown();
                System.out.println(Thread.currentThread().getName()+"finished.");
            }
        }.start();

    }
}
